package com.moralesce.gt.util;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;

/**
 * Provides utility methods for List instances.
 * 
 * @author Brandon Grenier
 */
public final class ListUtil {

	private ListUtil() {

	}

	/**
	 * Determines if the specifed list has duplicate elements.
	 * 
	 * @param list The list to check.
	 * 
	 * @return true if the specified list has duplicate elements, false
	 * otherwise.
	 */
	public static <T> boolean containsDuplicates(Collection<T> list) {
		return list == null ? false : new HashSet<T>(list).size() != list.size();
	}

	/**
	 * Merges the specified lists.
	 * 
	 * @param lists The lists to merge.
	 * 
	 * @return A List<T> containing all elements from the specified lists.
	 */
	public static <T> List<T> merge(List<T>... lists) {
		List<T> merged = new ArrayList<T>();
		for (List<T> list : lists) {
			merged.addAll(list);
		}
		return merged;
	}

	/**
	 * Creates and returns a copy of specified list.
	 * 
	 * @param list The list to copy.
	 * 
	 * @return A List<T>, as a copy of the original specified list.
	 */
	public static <T> List<T> copy(List<T> list) {
		List<T> copy = new ArrayList<T>();
		for (T element : list) {
			copy.add(element);
		}
		return copy;
	}

	/**
	 * Sorts the specified list in ascending order according to the natural
	 * ordering of its elements.
	 * 
	 * @param list The list to sort.
	 * 
	 * @return The specified list in ascending order according to the natural
	 * ordering of its elements.
	 */
	public static <T> List<T> sort(List<? extends Comparable> list) {
		Collections.sort(list);
		return (List<T>) list;
	}

	/**
	 * Sorts the specified list according to the order induced by the specified
	 * comparator.
	 * 
	 * @param list The list to sort.
	 * @param comparator The comparator.
	 * 
	 * @return The specified list according to the order induced by the
	 * specified comparator.
	 */
	public static <T> List<T> sort(List<T> list, Comparator comparator) {
		Collections.sort(list, comparator);
		return list;
	}

}
